import { defineStore } from 'pinia';
import { defaultLabelComponentList } from './defaultLabelComponentList';
import uuid from '../utils/uuid';

import { CompnoentUpadateInfo, ComponentDataType, TextCompnoentProps } from './storeTypes';
import { CSSProperties } from 'vue';

/* eg:
  [
    { id: uuid(), name: 'Text', props: { text: 'hello' } }
  ]
*/

export const componentStore = defineStore('componentData', {
  state: () => ({
    defaultLabelComponentList,
    components: [
      {
        id: uuid(),
        name: 'template-text',
        props: {
          tag: 'a',
          text: '测试内容 a',
          // 'https://cn.vitejs.dev/guide/'
          attr: { href: '#/template-editor' },
          style: {
            display: 'block',
            wdith: '100%',
            textAlign: 'center',
            color: '#0000ff',
            fontSize: '40px',
            lineHeight: '1.5',
            fontFamily: 'sans-serif'
          }
        },
        eventName: 'click',
        events: {
          click(e: MouseEvent) {
            console.log((e.target as HTMLElement).tagName);
          }
        }
      },
      {
        id: uuid(),
        name: 'template-text',
        props: {
          tag: 'h3',
          text: '测试内容 h3',
          style: { textAlign: 'center' }
        },
        // eventName: 'click',
        events: {
          click(e: MouseEvent) {
            console.log((e.target as HTMLElement).tagName);
          }
        }
      }
    ] as ComponentDataType[],
    currentComponent: ''
  }),
  actions: {
    addComponentData(component: ComponentDataType) {
      this.components.push({
        ...JSON.parse(JSON.stringify(component)),
        id: uuid()
      });
    },
    updateComponentData(props: CompnoentUpadateInfo) {
      // console.log(props);
      const item = this.components.find(({ id }) => id === this.currentComponent);
      if (item?.props) {
        switch (props.key) {
          case 'text':
            item.props.text = props.value as string;
            break;
          default:
            if (item.props.style) {
              item.props.style[props.key] = props.value;
            }
        }
      }
    }
  },
  getters: {
    getCurrentComponentInfo(state): TextCompnoentProps | null {
      const item = state.components.find(({ id }) => id === state.currentComponent);
      if (!item) return null;
      const _style = item.props.style as Required<CSSProperties & typeof item.props.style>;
      return { text: item.props.text, ..._style };
    }
  }
});
